package com.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Date;

public class JwtToken {

    String userName = "zhangsan";
    String secret = "1111111";//使用HMAC算法，111111作为密钥加密
    String token = "";


    @Test
    public void test01(){
        token = JWT.create()
                .withExpiresAt(new Date(System.currentTimeMillis()+100000))  //设置过期时间
                .withAudience(userName) //设置接受方信息，一般时登录用户
                .sign(Algorithm.HMAC256(secret));

        System.out.println("生成的token:"+token);

    }

    @Test
    public void test02(){

        //String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ6aGFuZ3NhbiIsImV4cCI6MTY3Mzc1MDI5NH0.7YLxhzjx5RmaFcOUnlEDREiFfZ3dfEVIeaIxWmGc4Cs";

        //从token中解析出来用户名
        String userName = JWT.decode(token).getAudience().get(0);
        System.out.println("用户名:"+userName);

    }

    @Test
    public void test03(){
        //String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ6aGFuZ3NhbiIsImV4cCI6MTY3Mzc1MDI5NH0.7YLxhzjx5RmaFcOUnlEDREiFfZ3dfEVIeaIxWmGc4Cs";
        test01();

        //验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        jwtVerifier.verify(token);//没报错说明验证成功
    }

}

